package m2;

import com.rabbitmq.client.*;

/*
    2022/1/20
    11:43
*/public class Consumer {
    public static void main(String[] args)throws Exception{
        //链接服务器
        ConnectionFactory f = new ConnectionFactory();
        f.setHost("192.168.64.140");
        f.setPort(5672); //5672用来收发消息 ，15672是管理控制台
        f.setUsername("admin");
        f.setPassword("admin");

        Connection connection = f.newConnection();
        Channel channel = connection.createChannel();

        //定义队列
        //如果队列在服务器已经存在，不会重复创建
        channel.queueDeclare("task_queue!",true,false,false,null);

        //创建回调对象
        DeliverCallback deliverCallback = (consumerTag, message) -> {
            String s = new String(message.getBody(), "UTF-8");
            System.out.println("收到:"+s);
            //遍历所有字符,模拟耗时任务
            for (int i = 0; i < s.length(); i++) {
                if (s.charAt(i) == '.') {
                    try {
                        System.out.println("消息正在处理......");
                        Thread.sleep(1000);
                    }catch (Exception e){}
                }
            }
            //发送回执basicAck(回执,是否对多条消息进行确认);
            channel.basicAck(message.getEnvelope().getDeliveryTag(),false);
            System.out.println("消息处理完成~");
        };
        //每次接受一条，处理完之前不接收下一条，手动Ack模式才有效
        channel.basicQos(1);


        CancelCallback cancelCallback = consumerTag -> {};

        //接收消息
        channel.basicConsume("task_queue!",false,deliverCallback,cancelCallback);
    }
}
